package com.chang.bootplus.config.security;

import cn.hutool.json.JSONUtil;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.base.utils.JwtUtils;
import com.chang.bootplus.entity.MatrixUser;
import com.chang.bootplus.service.MatrixUserService;
import com.chang.bootplus.vo.UserInfoVO;
import org.bouncycastle.pqc.math.linearalgebra.Matrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {




	@Autowired
	JwtUtils jwtUtils;

	@Autowired
	MatrixUserService matrixUserService;



	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

		MatrixUser byUsername = matrixUserService.getByUsername(authentication.getName());
		response.setContentType("application/json;charset=UTF-8");
		ServletOutputStream outputStream = response.getOutputStream();
		// 生成jwt，并放置到请求头中
		String jwt = jwtUtils.generateToken(authentication.getName());
		UserInfoVO userInfoVO = BeanUtil.beanA2beanB(byUsername, UserInfoVO.class);
		userInfoVO.setUserId(byUsername.getId());
		userInfoVO.setAvatar(byUsername.getAvatar());
		userInfoVO.setSex(byUsername.getSex());
		response.setHeader(jwtUtils.getHeader(), jwt);
		outputStream.write(JSONUtil.toJsonStr(new ApiResponse(userInfoVO).setReMsg("登录成功")).getBytes("UTF-8"));
		outputStream.flush();
		outputStream.close();
	}

}
